import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
// createRouter 创建路由实例
// 配置模式
// 1. hash模式: createWebHashHistory => 地址栏携带#
// 2. history模式: createWebHistory => 地址栏不携带#

// import.meta.env.BASE_URL: 路由前缀 => 可在vite.config中的base中配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 异步组件(路由懒加载)
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') }, // 登录页
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        }
      ]
    }
  ]
})

// 路由前置守卫
//  to: 需要去的页面
//  from: 当前准备离开的页面
//  当return false或者 undefined => 允许放行
//  当return '/login' { 'login' } => 拦截到对应的页面
router.beforeEach((to) => {
  const userStore = useUserStore()
  // 如果未登录访问需要授权页，则拦截到登录页
  if (!userStore.token && to.path !== '/login') {
    return '/login'
  }
})

export default router
